<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="参考： 菜鸟教程 https:&#x2F;&#x2F;www.runoob.com&#x2F;mysql&#x2F;mysql-transaction.html springboot使用@Transactional配置事务管理  https:&#x2F;&#x2F;blog.csdn.net&#x2F;nextyu&#x2F;article&#x2F;details&#x2F;78669997 springboot中事务的使用  https:&#x2F;&#x2F;blog.csdn.net&#x2F;feritylamb&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot中事务的使用">
<meta property="og:url" content="http://example.com/2021/04/14/springboot%E4%B8%AD%E4%BA%8B%E5%8A%A1%E7%9A%84%E4%BD%BF%E7%94%A8/index.html">
<meta property="og:site_name" content="yyc&#39;s blog">
<meta property="og:description" content="参考： 菜鸟教程 https:&#x2F;&#x2F;www.runoob.com&#x2F;mysql&#x2F;mysql-transaction.html springboot使用@Transactional配置事务管理  https:&#x2F;&#x2F;blog.csdn.net&#x2F;nextyu&#x2F;article&#x2F;details&#x2F;78669997 springboot中事务的使用  https:&#x2F;&#x2F;blog.csdn.net&#x2F;feritylamb&#x2F;">
<meta property="og:locale">
<meta property="article:published_time" content="2021-04-14T12:15:38.000Z">
<meta property="article:modified_time" content="2021-04-14T12:17:50.240Z">
<meta property="article:author" content="yyc">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://example.com/2021/04/14/springboot中事务的使用/"/>





  <title>springboot中事务的使用 | yyc's blog</title>
  








<meta name="generator" content="Hexo 5.3.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yyc's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">技术博客</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/04/14/springboot%E4%B8%AD%E4%BA%8B%E5%8A%A1%E7%9A%84%E4%BD%BF%E7%94%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yyc's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">springboot中事务的使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2021-04-14T20:15:38+08:00">
                2021-04-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/springboot/" itemprop="url" rel="index">
                    <span itemprop="name">springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>参考：</p>
<p>菜鸟教程 <a target="_blank" rel="noopener" href="https://www.runoob.com/mysql/mysql-transaction.html">https://www.runoob.com/mysql/mysql-transaction.html</a></p>
<p>springboot使用@Transactional配置事务管理  <a target="_blank" rel="noopener" href="https://blog.csdn.net/nextyu/article/details/78669997">https://blog.csdn.net/nextyu/article/details/78669997</a></p>
<p>springboot中事务的使用  <a target="_blank" rel="noopener" href="https://blog.csdn.net/feritylamb/article/details/95897955">https://blog.csdn.net/feritylamb/article/details/95897955</a></p>
<h2 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h2><blockquote>
<p>mysql事务主要用于操作量大、复杂度高的场景，比如管理系统中要删除一个成员，既要删除成员的基本资料（记录）也要删除相关人员的信息，如他发布的文章，评论，账目等等，这样一些列的数据库操作就构成一个事务。</p>
</blockquote>
<a id="more"></a>

<ul>
<li>mysql中只有使用了Innodb数据引擎的数据库或数据表才支持事务</li>
<li>事务处理可以用来维护数据库的完整性，保证sql语句要么全部执行，要么全部不执行</li>
<li>事务用来管理insert, update, delete语句</li>
</ul>
<p>事务必须满足的四个条件（ACID）：</p>
<p>原子性：要么全部完成，要么全部不完成。</p>
<p>一致性：事务开始之前和结束后数据库完整性没有被破坏（写入的数据符合所有预设）</p>
<p>隔离性：数据库允许多个并发事务同时对其数据进行读写和修改的能力。</p>
<p>持久性：事务处理后对数据的修改是永久的</p>
<h3 id="MYSQL-事务处理主要有两种方法："><a href="#MYSQL-事务处理主要有两种方法：" class="headerlink" title="MYSQL 事务处理主要有两种方法："></a>MYSQL 事务处理主要有两种方法：</h3><p>1、用 BEGIN, ROLLBACK, COMMIT来实现</p>
<ul>
<li><strong>BEGIN</strong> 开始一个事务</li>
<li><strong>ROLLBACK</strong> 事务回滚</li>
<li><strong>COMMIT</strong> 事务确认</li>
</ul>
<p>2、直接用 SET 来改变 MySQL 的自动提交模式:</p>
<ul>
<li><strong>SET AUTOCOMMIT=0</strong> 禁止自动提交</li>
<li><strong>SET AUTOCOMMIT=1</strong> 开启自动提交</li>
</ul>
<h3 id="springboot中事务的使用"><a href="#springboot中事务的使用" class="headerlink" title="springboot中事务的使用"></a>springboot中事务的使用</h3><blockquote>
<p>Spring 事务管理分为编程式和声明式的两种方式。编程式事务指的是通过编码方式实现事务；声明式事务基于 AOP,将具体业务逻辑与事务处理解耦。声明式事务管理使业务代码逻辑不受污染, 因此在实际使用中声明式事务用的比较多。声明式事务有两种方式，一种是在配置文件（xml）中做相关的事务规则声明，另一种是基于 @Transactional 注解的方式。</p>
</blockquote>
<p>springboot中通过给方法添加注解@Transactional 来实现事务</p>
<p><strong>测试：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Transactional</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@CacheEvict(value = &#123;&quot;articleCache&quot;,&quot;articleCaches&quot;&#125;, allEntries = true, beforeInvocation = true)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addArticle</span><span class="params">(Content content)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 校验参数是否为空</span></span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == content)</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Common.PARAM_IS_EMPTY);</span><br><span class="line">    <span class="keyword">if</span>(!StringUtils.hasLength(content.getTitle()))</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Article.TITLE_CAN_NOT_EMPTY);</span><br><span class="line">    <span class="keyword">if</span>(!StringUtils.hasLength(content.getContent()))</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Article.CONTENT_CAN_NOT_EMPTY);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 分类</span></span><br><span class="line">    String categories = content.getCategories();</span><br><span class="line"></span><br><span class="line">    contentMapper.addArticle(content);</span><br><span class="line">    <span class="keyword">int</span> cid = content.getCid();</span><br><span class="line">    <span class="comment">// 测试事务，抛出异常这里</span></span><br><span class="line">    <span class="keyword">if</span>(cid != <span class="number">0</span>)&#123;</span><br><span class="line">        <span class="keyword">throw</span> BusinessException.withErrorCode(ErrorConstant.Common.INVALID_PARAM);</span><br><span class="line">    &#125;</span><br><span class="line">    metaService.addMetas(cid, categories, Types.CATEGORY.getType());</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>测试结果是事务发生了回滚，数据插入不成功</p>
<p>若是不加事务注解，进行测试，异常抛出，文章也增加了。</p>
<p><strong>事务处理 @Transactional注解的使用</strong><br>Spring团队的建议是你在具体的类（或类的方法）上使用 @Transactional 注解，</p>
<p>而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解，但是这将只能当你设置了基于接口的代理时它才生效。因为注解是不能继承的，这就意味着如果你正在使用基于类的代理时，那么事务的设置将不能被基于类的代理所识别，而且对象也将不会被事务代理所包装（将被确认为严重的）。因此，请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。</p>
<p><strong>@Transactional 注解应该只被应用到 public 修饰的方法上。</strong> </p>
<p>如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解，它也不会报错， 但是这个被注解的方法将不会展示已配置的事务设置。<br><strong>Spring的AOP即声明式事务管理默认是针对unchecked exception回滚。</strong></p>
<p>也就是默认对RuntimeException()异常或是其子类进行事务回滚</p>
<p>（Spring事务管理只对出现运行期异常进行回滚）。checked异常,即Exception可try{}捕获的不会回滚，因此对于我们自定义异常，通过rollbackFor进行设定。如果我们需要捕获异常后，同时进行回滚，通过<code>TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();</code>进行手动回滚操作。</p>
<p>使用<code>Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint(); </code>设置回滚点，使用<code>TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);</code>回滚到savePoint。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2021/04/13/springboot%E4%B8%AD%E7%BC%93%E5%AD%98%E7%9A%84%E4%BD%BF%E7%94%A8/" rel="next" title="springboot中缓存的使用">
                <i class="fa fa-chevron-left"></i> springboot中缓存的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/04/17/blog%EF%BC%88%E4%B9%9D%EF%BC%89%E6%96%87%E7%AB%A0%E6%B7%BB%E5%8A%A0%E8%AF%84%E8%AE%BA-%E7%82%B9%E8%B5%9E/" rel="prev" title="blog（九）文章添加评论&点赞">
                blog（九）文章添加评论&点赞 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
                <a href="/archives">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8B%E5%8A%A1"><span class="nav-text">事务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#MYSQL-%E4%BA%8B%E5%8A%A1%E5%A4%84%E7%90%86%E4%B8%BB%E8%A6%81%E6%9C%89%E4%B8%A4%E7%A7%8D%E6%96%B9%E6%B3%95%EF%BC%9A"><span class="nav-text">MYSQL 事务处理主要有两种方法：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#springboot%E4%B8%AD%E4%BA%8B%E5%8A%A1%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-text">springboot中事务的使用</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yyc</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
